<template>
  <div class="container">
    <Top :signal="signal" :show="isShow" :quantileShow="false" />

    <div v-show="isVisible" class="main">
      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="info" label="名称" header-align="center" align="center" />
        <el-table-column
          v-for="(column, index) in tableColumns"
          :key="index"
          :prop="column.prop"
          :label="column.label"
          header-align="center"
          align="center"
        />
        <el-table-column prop="statistic" label="统计量（D值）" header-align="center" align="center" />
        <el-table-column prop="possibility" label="P值" header-align="center" align="center" />
      </el-table>

      <div class="text">
        <h3>说明<i class="el-icon-info" style="margin-left: 10px;" /></h3>
        差异性分析研究X(定类)对于Y(定量)的差异，比如不同学历人群对满意度差异关系；<br>
        第一：分析X与Y之间是否呈现出显著性(p值小于0.05或0.01)；<br>
        第二：如果呈现出显著性；通过具体对比平均值大小，描述具体差异所在；<br>
        第三：如果没有呈现出显著性；说明X不同组别下，Y没有差异；<br>
        第四：对分析进行总结。<br><br>
        <p>
          从上表可以看出，
          <span v-if="tableData.length">
            <span v-for="(item, idx) in tableData" :key="idx">
              <span v-show="item.possibility < 0.05">
                由于{{ item.possibility }} &lt; 0.05，对于{{ item.info }}而言，不同班级有显著差异。
              </span>
              <span v-show="item.possibility >= 0.05">
                由于{{ item.possibility }} &gt; 0.05，对于{{ item.info }}而言，不同班级没有显著差异。
              </span>
            </span>
          </span>
        </p>
      </div>

      <div class="chart-box">
        <div ref="chartRef1" class="chart" />
        <div ref="chartRef2" class="chart" />
      </div>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import Top from '../top'
import { variance } from '@/api/grades'
import { calcMedia, calcQuantile } from '@/utils/calc'
import * as echarts from 'echarts'
export default {
  name: 'Variance',
  components: {
    Top
  },
  data() {
    return {
      isVisible: false,
      tableData: [],
      tableColumns: [], // {label:'hhh',prop:'group1'}
      chart1: null,
      chart2: null,
      chartData: []
    }
  },
  mounted() {
    this.loadScript('https://echarts.apache.org/zh/js/vendors/echarts-simple-transform/dist/ecSimpleTransform.min.js')
  },
  methods: {
    signal(param) {
      variance(param.courseId, param.teacherId, param.semester).then(res => {
        this.clear()
        console.log('方差分析 => ', res)
        const data = res.data
        // 没有数据直接结束
        if (data === null) {
          // 隐藏
          this.isVisible = false
          Message({
            message: '只有一组数据',
            type: 'warning',
            duration: 2000
          })
          return
        }
        // 构造列信息
        let columnName; let i = 1
        data[0].itemList.forEach(item => {
          columnName = `group${i++}`
          // 构造列信息
          this.tableColumns.push({ label: `${item.info}（P25,P75）`, prop: columnName })
        })
        // 构造行
        for (let i = 0; i < data.length; i++) {
          const row = {}; const element = data[i]
          row.statistic = element.statistic.toFixed(2)
          row.possibility = element.possibility.toFixed(6)
          row.info = element.info
          for (let index = 0; index < this.tableColumns.length; index++) {
            const groupData = element.itemList[index].data
            row[this.tableColumns[index].prop] = `${calcMedia(groupData)}（${calcQuantile(groupData, 25)}，${calcQuantile(groupData, 75)}）`
          }
          this.tableData.push(row)
          // 生成图表的数据
          this[`chart${i + 1}Data`] = this.getData(element)
        }
        // 展示
        this.isVisible = true
        console.log('方差分析 => ', this.tableData)
        // 图表（箱线图）
        console.log('data', data)
        this.drawChart(data.length)
      })
    },
    isShow(isVisible) {
      this.isVisible = isVisible
    },
    clear() {
      this.tableData = []
      this.tableColumns = []
    },
    getData(data) {
      const ret = [['grade', 'class']]
      data.itemList.forEach(item => {
        item.data.forEach(score => {
          ret.push([score, item.info])
        })
      })
      return ret
    },
    drawChart(length) {
      console.log('drawChart')
      for (let i = 0; i < length; i++) {
        if (!this[`chart${i + 1}`]) {
          this[`chart${i + 1}`] = echarts.init(this.$refs[`chartRef${i + 1}`])
          this.draw(this[`chart${i + 1}Data`], this[`chart${i + 1}`], this.tableData[i].info)
        }
      }
    },
    draw(data, myChart, info) {
      console.log('draw')
      // eslint-disable-next-line
      echarts.registerTransform(ecSimpleTransform.aggregate)
      const option = {
        dataset: [
          {
            id: 'raw_data',
            source: data
          },
          {
            id: 'income_aggregate',
            fromDatasetId: 'raw_data',
            transform: [
              {
                type: 'ecSimpleTransform:aggregate',
                config: {
                  resultDimensions: [
                    { name: 'min', from: 'grade', method: 'min' },
                    { name: 'Q1', from: 'grade', method: 'Q1' },
                    { name: 'median', from: 'grade', method: 'median' },
                    { name: 'Q3', from: 'grade', method: 'Q3' },
                    { name: 'max', from: 'grade', method: 'max' },
                    { name: 'class', from: 'class' }
                  ],
                  groupBy: 'class'
                }
              }
            ]
          }
        ],
        title: {
          text: info
        },
        tooltip: {
          trigger: 'axis',
          confine: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          name: '分数',
          nameLocation: 'middle',
          nameGap: 30,
          scale: true
        },
        yAxis: {
          type: 'category'
        },
        grid: {
          bottom: 100
        },
        series: [
          {
            name: 'boxplot',
            type: 'boxplot',
            datasetId: 'income_aggregate',
            itemStyle: {
              color: '#b8c5f2'
            },
            encode: {
              x: ['min', 'Q1', 'median', 'Q3', 'max'],
              y: 'class',
              itemName: ['class'],
              tooltip: ['min', 'Q1', 'median', 'Q3', 'max']
            }
          }

        ]
      }
      myChart.setOption(option)
    },
    // 加载脚本
    loadScript(src) {
      // 动态加载脚本的方法
      const script = document.createElement('script')
      script.src = src
      document.head.appendChild(script)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30px;

  .main {
    margin-top: 30px;

    .text {
      margin: 30px 0 30px;
      background-color: #F3F9FE;
      padding: 10px;
    }

    .chart-box {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;

      .chart {
        width: 850px;
        height: 500px;
      }
    }
  }
}
</style>
